package com.example.design.ddd.practice.domain.orgmng.orgservice;

import com.example.design.ddd.practice.domain.common.validator.CommonValidator;
import com.example.design.ddd.practice.domain.orgmng.entity.Org;
import com.example.design.ddd.practice.domain.orgmng.entity.OrgStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Author liuzhihui
 * @Date 2024/6/3
 */
@Component
public class OrgHandler {

    private final CommonValidator commonValidator;
    private final OrgNameValidator nameValidator;
    private final OrgLeaderValidator leaderValidator;
    private CancelOrgValidator cancelValidator;

    @Autowired
    public OrgHandler(CommonValidator commonValidator, OrgNameValidator nameValidator, OrgLeaderValidator leaderValidator, CancelOrgValidator cancelValidator) {
        this.commonValidator = commonValidator;
        this.nameValidator = nameValidator;
        this.leaderValidator = leaderValidator;
        this.cancelValidator = cancelValidator;
    }

    public void updateBasic(Org org, String newName, Long newLeader, Long userId) {
        updateName(org, newName);
        updateLeader(org, newLeader);
        updateAuditInfo(org, userId);
    }

    public void cancel(Org org, Long userId) {
        cancelValidator.cancelledOrgShouldNotHasEmp(org.getTenantId(), org.getId());
        cancelValidator.OnlyEffectiveOrgCanBeCancelled(org);
        org.setStatus(OrgStatus.CANCELLED);
        updateAuditInfo(org, userId);
    }

    private void updateLeader(Org org, Long newLeader) {
        if (newLeader != null && !newLeader.equals(org.getLeaderId())) {
            leaderValidator.leaderShouldBeEffective(org.getTenantId(), newLeader);
            org.setLeaderId(newLeader);
        }
    }

    private void updateName(Org org, String newName) {
        if (newName != null && !newName.equals(org.getName())) {
            nameValidator.orgNameShouldNotEmpty(newName);
            nameValidator.nameShouldNotDuplicatedInSameSuperior(org.getTenantId(), org.getSuperiorId(), newName);
            org.setName(newName);
        }
    }

    private void updateAuditInfo(Org org, Long userId) { // 设置最后修改人和时间
    }
}
